﻿using UnityEngine;
using UnityEngine.Extension;
using System.Extension;
public class ActivationBehaviour : MonoBehaviour
{

    [SerializeField]
    ControlSubject m_subject = new ControlSubject(false);
    public ControlSubject subject { get { return m_subject; } }

    public bool inverseCondition = false, makeLast = true;
    public string text;
    bool preValue;
    void OnEnable()
    {
        if (subject.hasContent)
            SetActive(GetState());
    }

    void Start()
    {
        if (subject.hasContent)
            SetActive(GetState());
    }

    private bool GetState()
    {
        bool result = true;
        string value = subject.value.ToString();

        if (value.isNotNull())
        {
            result = (text == value);
            if (inverseCondition) result = !result;
        }
        return result;
    }

    private void SetActive(bool state)
    {
        gameObject.SetChildrenActive(state);
        gameObject.ForEachComponent<MonoBehaviour>(m => { if (m != this) m.enabled = state; });
        //if (state)
          //  gameObject.BroadcastMessage("Start");
        if (makeLast && state)
            transform.SetAsLastSibling();
    }

    void LateUpdate()
    {
        if (subject.hasUpdate)
            SetActive(GetState());
    }
}
